<?php
/**
 * Tcp服务
 *
 * @author		黑冰 <954650386@qq.com>
 */

namespace waf\server;

use \waf\Waf;
use \waf\log\WLog;
use \waf\server\BaseServer;
use \Yaf;

class TcpServer extends BaseServer
{
    public function init()
    {
        WLog::logSystem("in", __FILE__, __LINE__, __FUNCTION__);
        $this->strServerType = 'tcp';
        parent::init();
        WLog::logSystem("out", __FILE__, __LINE__, __FUNCTION__);
    }

    public function onReceive($objSServer, $fd, $from_id, $data)
    {
        WLog::logInfo("onReceive. data=".$data, __FILE__, __LINE__, __FUNCTION__);
        WLog::logDebug("work_id=".$objSServer->worker_id.', p_connect='.count($objSServer->connections), __FILE__, __LINE__, __FUNCTION__);

        $delimiter = Waf::getConfig('server', 'setting')['package_eof'];
        if($delimiter && $data)
        {
            $arrData    = explode($delimiter, $data);
            if($arrData && is_array($arrData))
            {
                foreach($arrData as $v)
                {
                    if($v)
                    {
                        $ret = $this->route($v);
                        if($ret['r'] === 0 && $ret['data'])
                        {
                            try {
                                ob_start();

                                $requestObj = new \Yaf_Request_Http($ret['data']['url']);
                                $this->setParams($requestObj, $ret['data']);
                                $this->objYaf->getDispatcher()->dispatch($requestObj);

                                $result = ob_get_contents();
                                ob_end_clean();
                                $objSServer->send($fd, $result);
                            } catch (\Throwable $e) {
                                WLog::logError("yaf_exception:".WLog::toJson(print_r($e, true)), __FILE__, __LINE__, __FUNCTION__);
                            }
                        }else{
                            WLog::logError("route data exception. receive_data = ".$data, __FILE__, __LINE__, __FUNCTION__);
                        }
                    }
                }
            }else{
                WLog::logError("route explode exception. delimiter = $delimiter, receive_data = ".$data, __FILE__, __LINE__, __FUNCTION__);
            }
        }else{
            WLog::logError("route data exception. delimiter = $delimiter, receive_data = ".$data, __FILE__, __LINE__, __FUNCTION__);
        }
    }
}
?>